package com.pig4cloud.pig.ads.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.pig.mapper.AdPicturePlatformMapper;
import com.pig4cloud.pig.ads.pig.mapper.PictureMapper;
import com.pig4cloud.pig.ads.service.AdPicturePlatformService;
import com.pig4cloud.pig.ads.service.PictureService;
import com.pig4cloud.pig.ads.utils.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.api.dto.AdPlanPictureLibDto;
import com.pig4cloud.pig.api.dto.UpdatePicTypeDto;
import com.pig4cloud.pig.api.entity.AdPicturePlatform;
import com.pig4cloud.pig.api.entity.PictureLib;
import com.pig4cloud.pig.api.util.UploadUtils;
import com.pig4cloud.pig.api.vo.PictureLibVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @description:
 * @author: nml
 * @time: 2020/10/29 19:08
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class PictureServiceImpl extends ServiceImpl<PictureMapper, PictureLib> implements PictureService {

	private final PictureMapper pictureMapper;

	private final AdPicturePlatformService adPicturePlatformService;

	private final AdPicturePlatformMapper adPicturePlatformMapper;


	@Value(value = "${upload.uploadUrl}")
	private String uploadUrl;

	@Value(value = "${upload.downloadUrl}")
	private String downloadUrl;

	@Value(value = "${upload.imgSize}")
	private String imgSize;

	/*广点通 广告创意处 图片库中选择一张图，判断是否已推送（单图片推送）*/
	@Override
	public R oneFileSynGdt(PictureLibVo req) {
		//图片id数组
		String[] idsGroup = req.getPids().split(",");
		String id1 = idsGroup[0];
		//获取多个广告账户id集合
		String[] advertiserIds = req.getAdvertiserIds();
		String advertiserId1 = advertiserIds[0];

		//根据图片id和广告账户id查询 图片推送信息表，如果未查询到则推送，查到记录则不推送。
		AdPicturePlatform picPlatform = adPicturePlatformMapper.selectOne(Wrappers.<AdPicturePlatform>query().lambda()
				.eq(AdPicturePlatform::getPictureId, id1)
				.eq(AdPicturePlatform::getAdvertiserId, advertiserId1)
				.last("LIMIT 1"));
		if (null == picPlatform) {//该图片未推送：推送
			//推送
			return adPicturePlatformService.uploadPicGdt(req);
		}
		//查询该条记录
		req.setCurrent(1);
		req.setSize(1);
		req.setId(Integer.parseInt(id1));
		req.setAdvertiserId(advertiserId1);
		AdPlanPictureLibDto data = pictureMapper.selectAdPlanPicSynData(req);
		return R.ok(data, "该图片已推送当前广告账户id");
	}

	@Override
	public R updatePType(UpdatePicTypeDto updatePicTypeDto) {
		Integer r = pictureMapper.updatePTypeById(updatePicTypeDto.getType(),updatePicTypeDto.getId());
		if(r <= 0){
			return R.failed("类型更新失败");
		}else {
			return R.ok("","保存成功");
		}
	}

	@Override
	public R oneFileSyn(PictureLibVo req) {
		Integer id = req.getId();
		String advertiserId = req.getAdvertiserId();
		//根据图片id和广告账户id查询 图片推送信息表，如果未查询到则推送，查到记录则不推送。
		AdPicturePlatform picPlatform = adPicturePlatformMapper.selectOne(Wrappers.<AdPicturePlatform>query().lambda()
				.eq(AdPicturePlatform::getPictureId, id)
				.eq(AdPicturePlatform::getAdvertiserId, advertiserId)
				.last("LIMIT 1"));
		if (null == picPlatform) {
			PictureLib pictureLib = pictureMapper.selectById(id);
			List<String> advList = Lists.newArrayList();
			advList.add(advertiserId);
			//推送
			boolean b = adPicturePlatformService.synPicture(pictureLib, advList);
			if (!b) {
				return R.failed("推送失败");
			}
		}
		//查询该条记录
		req.setCurrent(1);
		req.setSize(1);
		AdPlanPictureLibDto data = pictureMapper.selectAdPlanPicSynData(req);
		return R.ok(data, "该图片已推送当前广告账户id");
	}

	//图片本地上传到服务器：支持批量上传。图片信息逐条保存入库，获取返回id。
	// 返回 1、size：进度；2、id：图片id用来继续推送该图片
	@Override
	public R filesUpload(MultipartFile[] file) {
		try {
			//批量上传图片
			// 年月：如 202011;文件上传路径都加上年月文件夹，根据上传时间放在不同的年月目录下
			String ymPath = DateUtils.dateToString(new Date(), DateUtils.YYYYMM) + "/";
			//读取配置文件上传地址，真实路径
			uploadUrl = uploadUrl + ymPath;
			////读取配置文件下载url
			downloadUrl = downloadUrl + ymPath;
			long size = 50 * 1024 * 1024;
			//读取配置文件中设置的文件大小
			if (StringUtils.isNotBlank(imgSize) && !"null".equals(imgSize)) {
				size = Long.parseLong(imgSize);
			}

			Integer creator = SecurityUtils.getUser().getId();
			//遍历文件数组，执行图片上传及信息入库操作
			List<Map<String, Object>> filesStatusList = Lists.newArrayList();
			List<PictureLib> repeatPictureList = Lists.newArrayList();
			String msg = "";

			for (int i = 0; i < file.length; i++) {
				MultipartFile mFile = file[i];
				String md5 = DigestUtils.md5Hex(mFile.getInputStream());
				PictureLib pl = pictureMapper.selectOne(Wrappers.<PictureLib>query().lambda().eq(PictureLib::getMd5,md5).eq(PictureLib::getPictureStatus,"1").last("LIMIT 1"));
				if (null != pl){
					msg += "["+mFile.getOriginalFilename()+"]";
					repeatPictureList.add(pl);
				}else{
					Map<String, Object> resultMap = UploadUtils.imageUpload(uploadUrl, file[i], size);
					Integer code = (Integer) resultMap.get("code");
					Map<String, Object> filesStatus = new HashMap<String, Object>();
					//如果图片上传成功执行信息入库操作
					if (0 == code) {
						PictureLib pictureLib = new PictureLib();
						//文件新名称,这个方式的名称可能存在非法字符，导致图片文件同步失败。前端做图片名称校验
						//String picName = System.currentTimeMillis()+"_"+ file[i].getOriginalFilename();
						String picName = file[i].getOriginalFilename();
						pictureLib.setPictureName(picName);//图片名称
						//获取图片信息
						String filename = (String) resultMap.get("filename");
						pictureLib.setPictureFilename(filename);//图片文件名
						pictureLib.setPictureUrl(downloadUrl + filename);//图片访问url
						//获取图片宽高
						Double width = (Double) resultMap.get("width");
						String width1 = width.intValue() + "";
						Double height = (Double) resultMap.get("height");
						String height1 = height.intValue() + "";
						//新增字段：7个
						pictureLib.setWidth(width1);//图片宽
						pictureLib.setHeight(height1);//图片高
						pictureLib.setFormat((String) resultMap.get("format"));//图片格式
						pictureLib.setMd5((String) resultMap.get("md5"));
						pictureLib.setRealPath((String) resultMap.get("realPath"));
						pictureLib.setPSize(file[i].getSize() + "");//图片大小
						pictureLib.setScreenType(Integer.parseInt(resultMap.get("screenType").toString()));//图片横竖版
						//设置图片类型
						pictureLib.setPictureType(AdPicturePlatformServiceImpl.getPicType(width1, height1));
						pictureLib.setSourceType(1);//用户上传

						pictureLib.setPictureStatus("1");//图片状态
						pictureLib.setCreator(creator + "");//上传人creator
						pictureLib.setPictureSize(width1 + "*" + height1);//图片尺寸
						Date nowDate = new Date();
						pictureLib.setCreateTime(nowDate);
						pictureLib.setUpdateTime(nowDate);

						//上传成功就存记录
						this.save(pictureLib);

						//上传成功的图片信息
						filesStatus.put("fileName", file[i].getOriginalFilename());
						filesStatus.put("picFileName", filename);
						filesStatus.put("size", file[i].getSize());
						filesStatus.put("id", pictureLib.getId());
						filesStatus.put("pictureUrl", pictureLib.getPictureUrl());
						filesStatusList.add(filesStatus);
					} else {
						//上传失败的图片信息
						filesStatus.put("fileName", file[i].getOriginalFilename());
						filesStatus.put("picFileName", "");
						filesStatus.put("size", 0);
						filesStatus.put("id", "");
						filesStatus.put("pictureUrl", "");
						filesStatusList.add(filesStatus);
					}
				}
			}
			if (repeatPictureList.size() > 0){
				log.error("图片"+msg+"已经上传，推送后即可查看");
				return R.failed(repeatPictureList,100,"图片"+msg+"已经上传，推送后即可查看");
			} else {
				//图片全部上传且保存成功（若失败，size为0）
				return R.ok(filesStatusList, "操作成功");
			}
		} catch (IOException e) {
			e.printStackTrace();
			return R.failed("操作异常");
		}
	}

	//动态修改：图片名称可以重复（拉取的图片数据名称可以重复）
	@Override
	public R updateSelective(PictureLib pictureLib) {
		if (Objects.isNull(pictureLib)) {
			return R.failed("请选择图片");
		}
		if (null == pictureLib.getId()) {
			return R.failed("图片id不能为空");
		}
		pictureLib.setUpdateTime(new Date());//设置修改时间
		int i = 0;
		try {
			i = pictureMapper.updateByPrimaryKeySelective(pictureLib);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (i <= 0) {
			return R.failed("修改失败");
		}
		return R.ok("修改成功");
	}

	//删除图片或批量删除图片
	@Override
	public R delSelective(PictureLibVo pictureLibVo) {
		String pids = pictureLibVo.getPids();
		PictureLib pictureLib = new PictureLib();
		//单个id
		if (!pids.contains(",")) {
			int i = Integer.parseInt(pids);
			pictureLib.setId(i);
			pictureLib.setPictureStatus("0");//将图片状态设置为0，即为删除
			int del = pictureMapper.updateByPrimaryKeySelective(pictureLib);
			if (del == 1) {
				return R.ok(1, "删除成功");
			}
			return R.failed(0, "删除失败");
		}
		//多个id
		String[] pidsArr = pids.split(",");
		for (int i = 0; i < pidsArr.length; i++) {
			Integer id = Integer.parseInt(pidsArr[i]);
			pictureLib.setId(id);
			pictureLib.setPictureStatus("0");//将图片状态设置为0，即为删除
			int del = pictureMapper.updateByPrimaryKeySelective(pictureLib);
			if (del == 0) {
				return R.failed(0, "删除失败");
			}
		}
		return R.ok(1, "删除成功");
	}

}
